<?php

namespace Gds\VenteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Gds\VenteBundle\Form\DevisType;
use Gds\VenteBundle\Entity\Devis;
use Gds\VenteBundle\Entity\LigneDevis;
use Gds\VenteBundle\Entity\CategorieRemise;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Gds\VenteBundle\Entity\BonLivraisonClient;
use Gds\VenteBundle\Form\BonLivraisonClientType;
use Gds\VenteBundle\Entity\LigneBonLivraisonClient;
use Gds\VenteBundle\Entity\BonCommandeClient;
use Gds\VenteBundle\Form\BonCommandeClientType;
use Gds\VenteBundle\Entity\LigneBonCommandeClient;
use Gds\VenteBundle\Entity\HistoryBonLivraisonClient;
use Gds\VenteBundle\Entity\HistoryLigneBonLivraisonClient;

class DevisController extends Controller {

    public function indexAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $ref = $societe->getPrefixeDevis();
        $ref_num = $societe->getNumeroDevis();
        $devis = new Devis();
        $devis->setReference($ref . ' ' . $ref_num);
        $request = $this->getRequest();
        $form = $this->createForm(new DevisType, $devis);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                $heure = $request->get('heure');
                $form->bind($request);
                $devis = $form->getData();
                $client = $devis->getClient();
                $devis->setHeure($heure);
                $devis->setUser($this->getUser());
                $passager = false;
                if ($client->getRaisonSocial() == 'PASSAGER')
                    $passager = true;
                foreach ($articles->articles as $article) {
                    $ligne = new LigneDevis();
                    $art = $em->getRepository('GdsArticleBundle:Article')->find($article->id);
                    $ligne->setArticle($art);
                    $ligne->setQuantite($article->quantite);
                    $ligne->setTauxRemise($article->remise);
                    $ligne->setPrixUnitaireHt($article->prix_vente);
                    $ligne->setTauxTva($article->taux_tva);
                    $devis->addLignesDevi($ligne);
                    if (!$passager) {
                        $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $art));
                        if ($categorie_remise != null)
                            $categorie_remise->setRemise($article->remise);
                        else {
                            $categorie_remise = new CategorieRemise();
                            $categorie_remise->setArticle($art);
                            $categorie_remise->setClient($client);
                            $categorie_remise->setRemise($article->remise);
                        }
                        $em->persist($categorie_remise);
                    }
                }
                $ref_num = $societe->getNumeroDevis();
                $societe->setNumeroDevis($ref_num + 1);
                $devis->setReference($ref . ' ' . $ref_num);
                $devis->setUser($user);
                $em->persist($devis);
                $em->persist($societe);
                $em->flush();
                $response = new Response(json_encode(array('success' => true, 'id' => $devis->getId())));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        return $this->render('GdsVenteBundle:Devis:devis.html.twig', array('form' => $form->createView(), 'user' => $user));
    }

    public function editAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $devis = $em->getRepository('GdsVenteBundle:Devis')->find($id);

        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $prefixe_devis = $societe->getPrefixeDevis();
        $reference = $devis->getReference();
        $numero = str_replace($prefixe_devis, '', $reference);

        $devis->setMontantTtc(0);
        $form = $this->createForm(new DevisType, $devis);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            foreach ($devis->getLignesDevis() as $ligne) {
                $em->remove($ligne);
            }
            try {
                $articles = json_decode($request->get('articles'));
                $heure = $request->get('heure');
                $form->bind($request);
                $devis = $form->getData();
                $client = $devis->getClient();
                $devis->setHeure($heure);
                $devis->setUser($user);
                foreach ($articles->articles as $article) {
                    $ligne = new LigneDevis();
                    $art = $em->getRepository('GdsArticleBundle:Article')->find($article->id);
                    $ligne->setArticle($art);
                    $ligne->setQuantite($article->quantite);
                    $ligne->setTauxRemise($article->remise);
                    $ligne->setPrixUnitaireHt($article->prix_vente);
                    $ligne->setTauxTva($article->taux_tva);
                    $devis->addLignesDevi($ligne);
                    $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $art));
                    if ($categorie_remise != null)
                        $categorie_remise->setRemise($article->remise);
                    else {
                        $categorie_remise = new CategorieRemise();
                        $categorie_remise->setArticle($art);
                        $categorie_remise->setClient($client);
                        $categorie_remise->setRemise($article->remise);
                    }
                    $em->persist($categorie_remise);
                }
                $em->persist($devis);
                $em->flush();
                $response = new Response(json_encode(array('success' => true, 'id' => $devis->getId())));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        $time = $devis->getTime();
        $heure = $devis->getHeure();
        $lignes = array();
        foreach ($devis->getLignesDevis() as $k => $ligne) {
            $lignes[$k] = $ligne;
        }
        return $this->render('GdsVenteBundle:Devis:devis_edit.html.twig', array('form' => $form->createView(), 'heure' => $heure, 'time' => $time, 'lignes' => $lignes, 'id' => $id, 'user' => $user, 'devis' => $devis));
    }

    public function duppliquerAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $old_devis = $em->getRepository('GdsVenteBundle:Devis')->find($id);
        $devis = clone $old_devis;
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $pref = $societe->getPrefixeDevis();
        $num = $societe->getNumeroDevis();
        $devis->setReference($pref . ' ' . $num);
        $devis->setMontantTtc(0);
        $form = $this->createForm(new DevisType, $devis);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                $heure = $request->get('heure');
                $form->bind($request);
                $devis = $form->getData();
                $client = $devis->getClient();
                $devis->setHeure($heure);
                foreach ($articles->articles as $article) {
                    $ligne = new LigneDevis();
                    $art = $em->getRepository('GdsArticleBundle:Article')->find($article->id);
                    $ligne->setArticle($art);
                    $ligne->setQuantite($article->quantite);
                    $ligne->setTauxRemise($article->remise);
                    $ligne->setPrixUnitaireHt($article->prix_vente);
                    $ligne->setTauxTva($article->taux_tva);
                    $devis->addLignesDevi($ligne);
                    $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $art));
                    if ($categorie_remise != null)
                        $categorie_remise->setRemise($article->remise);
                    else {
                        $categorie_remise = new CategorieRemise();
                        $categorie_remise->setArticle($art);
                        $categorie_remise->setClient($client);
                        $categorie_remise->setRemise($article->remise);
                    }
                    $em->persist($categorie_remise);
                }
                $ref_num = $societe->getNumeroDevis();
                $societe->setNumeroDevis($ref_num + 1);
                $devis->setReference($pref . ' ' . $ref_num);
                $devis->setUser($user);
                $em->persist($societe);
                $em->persist($devis);
                $em->flush();
                $response = new Response(json_encode(array('success' => true, 'numero' => $ref_num)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        $time = $devis->getTime();
        $heure = $devis->getHeure();
        $lignes = array();
        foreach ($devis->getLignesDevis() as $k => $ligne) {
            $lignes[$k] = $ligne;
        }
        return $this->render('GdsVenteBundle:Devis:devis_duppliquer.html.twig', array('form' => $form->createView(), 'heure' => $heure, 'time' => $time, 'lignes' => $lignes, 'id' => $id, 'user' => $user));
    }

    public function deleteAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $devis = $em->getRepository('GdsVenteBundle:Devis')->find($id);
        $devis->setIsSupprimer(true);
        $em->persist($devis);
        $em->flush();
        return new Response('success');
    }

    public function showAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $devis = $em->getRepository('GdsVenteBundle:Devis')->find($id);
        $lignes_devis = $em->getRepository('GdsVenteBundle:LigneDevis')->findByDevis($devis);
        $lignes = $em->getRepository('GdsVenteBundle:LigneDevis')->findBy(array('devis' => $devis), array('taux_tva' => 'ASC'));
        $taxes = array();
        foreach ($lignes as $ligne) {
            $tva = $ligne->getTauxTva();
            $base = $ligne->getQuantite() * $ligne->getPrixUnitaireHt() * (1 - $ligne->getTauxRemise() / 100);
            $montant = $base * $tva / 100;
            $exist = false;
            foreach ($taxes as $k => $taxe) {
                if (!$exist && $taxe['tva'] == $tva) {
                    $taxes[$k]['base']+=$base;
                    $taxes[$k]['montant']+=$montant;
                    $exist = true;
                }
            }
            if (!$exist) {
                $taxe = array();
                $taxe['tva'] = $tva;
                $taxe['base'] = $base;
                $taxe['montant'] = $montant;
                $taxes[count($taxes)] = $taxe;
            }
        }
        return $this->render('GdsVenteBundle:Devis:devis_show.html.twig', array('devis' => $devis, 'lignes' => $lignes_devis, 'taxes' => $taxes, 'id' => $id));
    }

    public function printDevisSavedAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $prefixe_devis = $societe->getPrefixeDevis();
        $id = $request->get('id');
        $devis = $em->getRepository('GdsVenteBundle:Devis')->find($id);
        $reference = $devis->getReference();
        $numero = str_replace($prefixe_devis, '', $reference);
        $lignes = $em->getRepository('GdsVenteBundle:LigneDevis')->findByDevis($devis);


        $facade = $this->get('ps_pdf.facade');
        $response = new Response();
        $total_brut = 0;
        $remise = 0;
        $total_tva = 0;
        foreach ($lignes as $ligne) {
            $prix = $ligne->getQuantite() * $ligne->getPrixUnitaireHt();
            $total_brut += $prix;
            $remise += $prix * $ligne->getTauxRemise() / 100;
            $total_tva += $prix * (1 - $ligne->getTauxRemise() / 100) * $ligne->getTauxTva() / 100;
        }
        $total_ht = $total_brut - $remise;
        $total_ttc = $total_ht + $total_tva;
        $total_ttc = round($total_ttc, 3);
        $montant_lettre = $this->chiffre_to_lettre($total_ttc);
        $this->render('GdsVenteBundle:Devis:devis_saved.pdf.twig', array('lignes' => $lignes, 'numero' => $numero, 'total_ttc' => $total_ttc, 'total_brut' => $total_brut, 'remise' => $remise, 'total_ht' => $total_ht, 'total_tva' => $total_tva, 'montant_lettre' => $montant_lettre, 'devis' => $devis), $response);
        $xml = $response->getContent();
        $content = $facade->render($xml);
        file_put_contents('uploads/devis_saved.pdf', $content);
        exec("printdevissaved.vbs");
        return new Response(json_encode(array('success' => true)));
    }

    public function beneficeAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $key = $request->get('key');
        $code = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0]->getCodeBenefice();
        if ($key != $code)
            return new Response('failed');
        $nom_dep = $request->get('departement');
        $is_facturable = $request->get('facturable');
        $contenu = json_decode($request->get('contenu'));
        $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
        $benefices = array();
        $quantites = array();
        foreach ($contenu->lignes as $a => $ligne) {
            $article = $em->getRepository('GdsArticleBundle:Article')->find($ligne->id);
            $array_stocks_achat = array();
            if ($departement != null) {
                $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                if ($is_facturable == 'true')
                    $array_stocks_achat[0] = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock, 'is_noir' => 0), array('prix_achat_ttc' => 'ASC'));
                else
                    $array_stocks_achat[0] = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock), array('is_noir' => 'DESC', 'prix_achat_ttc' => 'ASC'));
            }else {
                $stocks = $em->getRepository('GdsArticleBundle:Stock')->findByArticle($article);
                foreach ($stocks as $k => $stock) {
                    if ($is_facturable == 'true')
                        $array_stocks_achat[$k] = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock, 'is_noir' => 0), array('prix_achat_ttc' => 'ASC'));
                    else
                        $array_stocks_achat[$k] = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock), array('is_noir' => 'DESC', 'prix_achat_ttc' => 'ASC'));
                }
            }
            $st = array();
            foreach ($array_stocks_achat as $stocks_achat) {
                foreach ($stocks_achat as $stock_achat) {
                    $index = count($st);
                    $st[$index]['qte'] = $stock_achat->getQuantite();
                    $st[$index]['prix_achat'] = $stock_achat->getPrixAchatTtc();
                }
            }
            $benefices[$a] = $this->getBenefice($ligne, $st, $em);
            $quantite = array();
            if ($departement != null) {
                $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                $quantite['qte'] = floatval($stock->getQuantiteBlanc());
                $quantite['qte_2'] = floatval($stock->getQuantiteNoir());
            }
            $stocks = $em->getRepository('GdsArticleBundle:Stock')->findByArticle($article);
            $quantite['qte_all'] = 0;
            $quantite['qte_all_2'] = 0;
            foreach ($stocks as $stock) {
                $quantite['qte_all']+= $stock->getQuantiteBlanc();
                $quantite['qte_all_2']+= $stock->getQuantiteNoir();
            }
            $quantites[$a] = $quantite;
        }
        $result = array();
        $result['benefice'] = $benefices;
        $result['qte'] = $quantites;
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    function getBenefice($ligne, $st, $em) {
        $quantite = $ligne->quantite;
        $total = $ligne->total;
        $prix_vente = $total / $quantite;
        if ($st == null) {
            $article = $em->getRepository('GdsArticleBundle:Article')->find($ligne->id);
            $prix_achat = $article->getPrixAchatHt() * (1 + $article->getTauxTva() / 100);
            $benefice = $quantite * ($prix_vente - $prix_achat);
            return $benefice;
        }
        $benefice = 0;
        $i = 0;
        $count_st = count($st);
        while ($quantite > 0 && $i < $count_st) {
            if ($st[$i]['qte'] >= $quantite) {
                $benefice += $quantite * ($prix_vente - $st[$i]['prix_achat']);
                return $benefice;
            } else {
                $benefice += $st[$i]['qte'] * ($prix_vente - $st[$i]['prix_achat']);
                $quantite -= $st[$i]['qte'];
            }
            $i++;
        }
        if ($quantite > 0) {
            $article = $em->getRepository('GdsArticleBundle:Article')->find($ligne->id);
            $prix_achat = $article->getPrixAchatHt() * (1 + $article->getTauxTva() / 100);
            $benefice += ($quantite * ($prix_vente - $prix_achat));
        }
        return $benefice;
    }

    public function remiseDepasseAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $key = $request->get('pass_remise');
        $code = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0]->getCodeRemise();
        if ($key != $code) {
            return new Response('failed');
        }
        return new Response('success');
    }

    public function quantiteDisponibleNoirAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $key = $request->get('key');
        $code = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0]->getCodeQuantite();
        if ($key != $code) {
            return new Response('failed');
        }
        $nom_dep = $request->get('departement');
        $contenu = json_decode($request->get('contenu'));
        $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
        $quantites = array();
        foreach ($contenu->lignes as $k => $ligne) {
            $quantite = array();
            $article = $em->getRepository('GdsArticleBundle:Article')->find($ligne->id);
            if ($departement != null) {
                $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                $quantite['qte'] = floatval($stock->getQuantiteBlanc());
                $quantite['qte_2'] = floatval($stock->getQuantiteNoir());
            }
            $stocks = $em->getRepository('GdsArticleBundle:Stock')->findByArticle($article);
            $quantite['qte_all'] = 0;
            $quantite['qte_all_2'] = 0;
            foreach ($stocks as $stock) {
                $quantite['qte_all']+= $stock->getQuantiteBlanc();
                $quantite['qte_all_2']+= $stock->getQuantiteNoir();
            }
            $quantites[$k] = $quantite;
        }
        $response = new Response(json_encode($quantites));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function quantiteDisponibleAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $nom_dep = $request->get('departement');
        $reference = $request->get('reference');
        $article = $em->getRepository('GdsArticleBundle:Article')->findOneByReference($reference);
        if ($article == null) {
            return new Response('failed');
        }
        $quantite = array();
        $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
        if ($departement != null) {
            $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
            $quantite['qte'] = floatval($stock->getQuantiteBlanc());
            $quantite['qte_2'] = floatval($stock->getQuantiteNoir());
        }
        $stocks = $em->getRepository('GdsArticleBundle:Stock')->findByArticle($article);
        $quantite['qte_all'] = 0;
        $quantite['qte_all_2'] = 0;
        foreach ($stocks as $stock) {
            $quantite['qte_all']+= $stock->getQuantiteBlanc();
            $quantite['qte_all_2']+= $stock->getQuantiteNoir();
        }
        $response = new Response(json_encode($quantite));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function allQuantiteDisponibleAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $nom_dep = $request->get('departement');
        $references = json_decode($request->get('references'));
        $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
        $quantites = array();
        foreach ($references as $reference) {
            $article = $em->getRepository('GdsArticleBundle:Article')->findOneByReference($reference);
            $quantite = array();
            if ($departement != null) {
                $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                $quantite['qte'] = floatval($stock->getQuantiteBlanc());
                $quantite['qte_2'] = floatval($stock->getQuantiteNoir());
            }
            $stocks = $em->getRepository('GdsArticleBundle:Stock')->findByArticle($article);
            $quantite['qte_all'] = 0;
            $quantite['qte_all_2'] = 0;
            foreach ($stocks as $stock) {
                $quantite['qte_all']+= $stock->getQuantiteBlanc();
                $quantite['qte_all_2']+= $stock->getQuantiteNoir();
            }
            $quantites[] = $quantite;
        }
        $response = new Response(json_encode($quantites));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getAllDevisAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $num = $request->get('numero');
        $raison = $request->get('raison_social');
        $date1 = $request->get('date1');
        $date2 = $request->get('date2');
        $heure1 = $request->get('heure1');
        $heure2 = $request->get('heure2');
        $ref = $request->get('reference');
        $des = $request->get('designation');
        $ttc1 = $request->get('ttc1');
        $ttc2 = $request->get('ttc2');
        $query = $em->getRepository('GdsVenteBundle:Devis')->getResult($num, $raison, $date1, $date2, $heure1, $heure2, $ref, $des, $ttc1, $ttc2);
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $query, $request->get('page', 1)/* page number */, 10/* limit per page */
        );

        if ($request->get('type')) {
            return $this->render('GdsVenteBundle:Devis:page_liste_devis.html.twig', array('pagination' => $pagination));
        }
        if ($request->get('retour') != "")
            return $this->render('GdsVenteBundle:Devis:liste_devis.html.twig', array('pagination' => $pagination));
        return $this->render('GdsVenteBundle:Devis:all_devis.html.twig', array('pagination' => $pagination));
    }

    public function getAllArticlesAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $client_id = $request->get('client_id');
        $raison_social = $request->get('raison_social');
        if ($raison_social)
            $client = $em->getRepository('GdsVenteBundle:Client')->findOneBy(array('raison_social' => $raison_social));
        else
            $client = $em->getRepository('GdsVenteBundle:Client')->find($client_id);
        $articles = $em->getRepository('GdsArticleBundle:Article')->findAll();
        $result = array();
        $k = 0;
        $passager = false;
        if ($raison_social == 'PASSAGER')
            $passager = true;
        foreach ($articles as $article) {
            if ($article->getIsSupprimer() == false) {
                $result[$k]['designation'] = $article->getDesignation();
                $result[$k]['reference'] = $article->getReference();
                $result[$k]['taux_tva'] = $article->getTauxTva();
                if ($passager)
                    $result[$k]['remise'] = $article->getRemise();
                else {
                    $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
                    if ($categorie_remise != null)
                        $result[$k]['remise'] = $categorie_remise->getRemise();
                    else
                        $result[$k]['remise'] = $article->getRemise();
                }
                $result[$k]['remise_max'] = $article->getRemiseMax();
                $result[$k]['prix_vente'] = $article->getPrixVente();
                $result[$k]['quantite'] = 1;
                $result[$k]['prix_vente_min_ttc'] = $article->getPrixVente() * (1 + $article->getTauxTva() / 100) * (1 - $article->getRemiseMax() / 100);
                $name = $article->getReference() . ' : ' . $article->getDesignation() . ' : ' . $article->getCodeBarre();
                $result[$k]['name'] = $name;
                $result[$k]['id'] = $article->getId();
                $k++;
            }
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getRemisesClientAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id_client = $request->get('client_id');
        $client = $em->getRepository('GdsVenteBundle:Client')->find($id_client);
        $raison_social = $client->getRaisonSocial();
        $articles = $request->get('articles');
        $passager = false;
        if ($raison_social == 'PASSAGER')
            $passager = true;
        else
            $client = $em->getRepository('GdsVenteBundle:Client')->findOneBy(array('raison_social' => $raison_social));
        $remises = array();
        foreach ($articles as $k => $art) {
            $article = $em->getRepository('GdsArticleBundle:Article')->find($art);
            if ($passager)
                $remises[$k] = $article->getRemise();
            else {
                $cat = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
                if ($cat != null) {
                    $remises[$k] = $cat->getRemise();
                } else {
                    $remises[$k] = $article->getRemise();
                }
            }
        }
        $response = new Response(json_encode($remises));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getAllFamillesAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $familles = $em->getRepository('GdsArticleBundle:Famille')->findAll();
        $result = array();
        $k = 0;
        foreach ($familles as $famille) {
            if ($famille->getIsSupprimer() == 0) {
                $result[$k]['name'] = $famille->getLibelle();
                $result[$k]['id'] = $famille->getId();
                $k++;
            }
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getSousFamillesWhereFamillesAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $familles = json_decode($request->get('familles'));
        $result = array();
        $k = 0;
        foreach ($familles->familles as $id_famille) {
            $famille = $em->getRepository('GdsArticleBundle:Famille')->find($id_famille);
            $sous_familles = $em->getRepository('GdsArticleBundle:Famille')->getSousFamilles($famille);
            if ($sous_familles == null) {
                $result[$k]['name'] = $famille->getLibelle();
                $result[$k]['id'] = $famille->getId();
                $k++;
            } else {
                foreach ($sous_familles as $sous_famille) {
                    $result[$k]['name'] = $sous_famille->getLibelle();
                    $result[$k]['id'] = $sous_famille->getId();
                    $k++;
                }
            }
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getArticlesWhereFamillesAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        if ($request->get('raison_social')) {
            $raison_social = $request->get('raison_social');
            $client = $em->getRepository('GdsVenteBundle:Client')->findOneBy(array('raison_social' => $raison_social));
        }
        if ($request->get('client_id')) {
            $client_id = $request->get('client_id');
            $client = $em->getRepository('GdsVenteBundle:Client')->find($client_id);
        }
        $familles = json_decode($request->get('familles'));
        $sous_familles = $familles->sous_familles;
        if (count($sous_familles) == 0) {
            $familles = $familles->familles;
            $all_familles = $familles;
            foreach ($familles as $famille) {
                $sous_familles = $em->getRepository('GdsArticleBundle:Famille')->findBy(array('famille_mere' => $famille, 'is_supprimer' => 0));
                foreach ($sous_familles as $sous_famille)
                    array_push($all_familles, $sous_famille->getId());
            }
            $familles = $all_familles;
        } else
            $familles = $familles->sous_familles;
        $result = array();
        $k = 0;
        foreach ($familles as $id_famille) {
            $articles = $em->getRepository('GdsArticleBundle:Article')->findByFamille($id_famille);
            foreach ($articles as $article) {
                if ($article->getIsSupprimer() == false) {
                    $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
                    $result[$k]['designation'] = $article->getDesignation();
                    $result[$k]['reference'] = $article->getReference();
                    $result[$k]['taux_tva'] = $article->getTauxTva();
                    if ($categorie_remise != null)
                        $result[$k]['remise'] = $categorie_remise->getRemise();
                    else
                        $result[$k]['remise'] = $article->getRemise();
                    $result[$k]['remise_max'] = $article->getRemiseMax();
                    $result[$k]['prix_vente'] = $article->getPrixVente();
                    $result[$k]['quantite'] = 1;
                    $result[$k]['prix_vente_min_ttc'] = $article->getPrixVente() * (1 + $article->getTauxTva() / 100) * (1 - $article->getRemiseMax() / 100);
                    $name = $article->getReference() . ' : ' . $article->getDesignation();
                    $result[$k]['name'] = $name;
                    $result[$k]['id'] = $article->getId();
                    $k++;
                }
            }
        }
        if (count($familles) == 0) {
            $articles = $em->getRepository('GdsArticleBundle:Article')->findAll();
            foreach ($articles as $article) {
                if ($article->getIsSupprimer() == false) {
                    $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
                    $result[$k]['designation'] = $article->getDesignation();
                    $result[$k]['reference'] = $article->getReference();
                    $result[$k]['taux_tva'] = $article->getTauxTva();
                    if ($categorie_remise != null)
                        $result[$k]['remise'] = $categorie_remise->getRemise();
                    else
                        $result[$k]['remise'] = $article->getRemise();
                    $result[$k]['remise_max'] = $article->getRemiseMax();
                    $result[$k]['prix_vente'] = $article->getPrixVente();
                    $result[$k]['quantite'] = 1;
                    $result[$k]['prix_vente_min_ttc'] = $article->getPrixVente() * (1 + $article->getTauxTva() / 100) * (1 - $article->getRemiseMax() / 100);
                    $name = $article->getReference() . ' : ' . $article->getDesignation();
                    $result[$k]['name'] = $name;
                    $result[$k]['id'] = $article->getId();
                    $k++;
                }
            }
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getAllDepartementAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $departements = $em->getRepository('GdsArticleBundle:Departement')->findAll();
        return $this->render('GdsVenteBundle:Devis:departement.html.twig', array('departements' => $departements));
    }

    public function getDesignationsAutocompleteAction(Request $request) {
        $chaine = $request->query->get('term');
        $em = $this->getDoctrine()->getEntityManager();
        $articles = $em->getRepository('GdsArticleBundle:Article')->getDesignations($chaine);
        $result = array();
        foreach ($articles as $k => $article) {
            $result[$k]['label'] = $article->getDesignation();
            $result[$k]['reference'] = $article->getReference();
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getReferencesAutocompleteAction(Request $request) {
        $chaine = $request->query->get('term');
        $em = $this->getDoctrine()->getEntityManager();
        $articles = $em->getRepository('GdsArticleBundle:Article')->getReferences($chaine);
        $result = array();
        foreach ($articles as $k => $article) {
            $result[$k]['label'] = $article->getReference();
            $result[$k]['designation'] = $article->getDesignation();
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getDesignationWhereReferenceAction(Request $request) {
        $reference_libelle = $request->query->get('reference');
        $em = $this->getDoctrine()->getEntityManager();
        $article = $em->getRepository('GdsArticleBundle:Article')->findOneByReference($reference_libelle);
        $designation = null;
        if ($article != null && $article->getIsSupprimer() == 0)
            $designation = $article->getDesignation();
        return new Response($designation);
    }

    public function getReferenceWhereDesignationAction(Request $request) {
        $designation_libelle = $request->query->get('designation');
        $em = $this->getDoctrine()->getEntityManager();
        $article = $em->getRepository('GdsArticleBundle:Article')->findOneByDesignation($designation_libelle);
        $reference = null;
        if ($article != null && $article->getIsSupprimer() == 0)
            $reference = $article->getReference();
        return new Response($reference);
    }

    public function getDesignationsAction(Request $request) {
        $chaine = $request->query->get('term');
        $raison_social = $request->query->get('raison_social');
        $em = $this->getDoctrine()->getEntityManager();
        $client = $em->getRepository('GdsVenteBundle:Client')->find($raison_social);
        $articles = $em->getRepository('GdsArticleBundle:Article')->getDesignations($chaine);
        $result = array();
        foreach ($articles as $k => $article) {
            $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->getRemiseClient($client, $article);
            $result[$k]['label'] = $article->getDesignation();
            $result[$k]['reference'] = $article->getReference();
            $result[$k]['taux_tva'] = $article->getTauxTva();
            if ($categorie_remise != null)
                $result[$k]['remise'] = $categorie_remise->getRemise();
            else
                $result[$k]['remise'] = $article->getRemise();
            $result[$k]['prix_vente'] = $article->getPrixVente();
            $result[$k]['article'] = $article->getId();
            $result[$k]['remise_client'] = $article->getRemise();
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getReferencesAction(Request $request) {
        $chaine = $request->query->get('term');
        $raison_social = $request->query->get('raison_social');
        $em = $this->getDoctrine()->getEntityManager();
        $client = $em->getRepository('GdsVenteBundle:Client')->find($raison_social);
        $articles = $em->getRepository('GdsArticleBundle:Article')->getReferences($chaine);
        $result = array();
        foreach ($articles as $k => $article) {
            $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->getRemiseClient($client, $article);
            $result[$k]['label'] = $article->getReference();
            $result[$k]['reference'] = $article->getReference();
            $result[$k]['designation'] = $article->getDesignation();
            $result[$k]['taux_tva'] = $article->getTauxTva();
            if ($categorie_remise != null)
                $result[$k]['remise'] = $categorie_remise->getRemise();
            else
                $result[$k]['remise'] = $article->getRemise();
            $result[$k]['prix_vente'] = $article->getPrixVente();
            $result[$k]['article'] = $article->getId();
            $result[$k]['remise_client'] = $article->getRemise();
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getAllWhereDesignationAction(Request $request) {
        $raison_social = $request->query->get('raison_social');
        $designation = $request->query->get('designation');
        $em = $this->getDoctrine()->getEntityManager();
        $client = $em->getRepository('GdsVenteBundle:Client')->findOneById($raison_social);
        $article = $em->getRepository('GdsArticleBundle:Article')->getAllByDesignation($designation);
        $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->getRemiseClient($client, $article);
        $result = array();
        if ($article != null) {
            $result['reference'] = $article->getReference();
            $result['designation'] = $designation;
            $result['taux_tva'] = $article->getTauxTva();
            if ($categorie_remise != null)
                $result['remise'] = $categorie_remise->getRemise();
            else
                $result['remise'] = $article->getRemise();
            $result['prix_vente'] = $article->getPrixVente();
            $result['prix_vente_client'] = $article->getPrixVente();
            $result['prix_vente_min'] = $result['prix_vente'] * (1 - ($article->getRemiseMax() / 100));
            $result['article'] = $article->getId();
            $result['remise_client'] = $article->getRemise();
            $result['quantite'] = 1;
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function getAllWhereReferenceAction(Request $request) {
        $raison_social = $request->query->get('raison_social');
        $reference = $request->query->get('reference');
        $em = $this->getDoctrine()->getEntityManager();
        $client = $em->getRepository('GdsVenteBundle:Client')->findOneById($raison_social);
        $article = $em->getRepository('GdsArticleBundle:Article')->getAllByReference($reference);
        $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->getRemiseClient($client, $article);
        $result = array();
        if ($article != null) {
            $result['reference'] = $reference;
            $result['designation'] = $article->getDesignation();
            $result['taux_tva'] = $article->getTauxTva();
            if ($categorie_remise != null)
                $result['remise'] = $categorie_remise->getRemise();
            else
                $result['remise'] = $article->getRemise();
            $result['prix_vente'] = $article->getPrixVente();
            $result['prix_vente_client'] = $article->getPrixVente();
            $result['prix_vente_min'] = $result['prix_vente'] * (1 - ($article->getRemiseMax() / 100));
            $result['article'] = $article->getId();
            $result['remise_client'] = $article->getRemise();
            $result['quantite'] = 1;
        }
        $response = new Response(json_encode($result));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function commanderAction() {
        $request = $this->getRequest();
        $id = $request->get('id');
        $em = $this->getDoctrine()->getEntityManager();
        $devis = $em->getRepository('GdsVenteBundle:Devis')->find($id);
        $bon_commande = new BonCommandeClient();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $pref = $societe->getPrefixeBonCommandeClient();
        $num = $societe->getNumeroBonCommandeClient();
        $bon_commande->setReference($pref . ' ' . $num);
        $form = $this->createForm(new BonCommandeClientType, $bon_commande);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                $heure = $request->get('heure');
                $nom_dep = $request->get('departement');
                $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
                $form->bind($request);
                $bon_commande = $form->getData();
                $bon_commande->setHeure($heure);
                foreach ($articles->articles as $article) {
                    $ligne = new LigneBonCommandeClient();
                    $art = $em->getRepository('GdsArticleBundle:Article')->find($article->id);
                    $ligne->setArticle($art);
                    $ligne->setQuantite($article->quantite);
                    $bon_commande->addLignesBonCommande($ligne);
                }
                $ref_num = $societe->getNumeroBonCommandeClient();
                $societe->setNumeroBonCommandeClient($ref_num + 1);
                $bon_commande->setDepartement($departement);
                $bon_commande->setReference($pref . ' ' . $ref_num);
                $bon_commande->setUser($user);
                $bon_commande->setDevis($devis);
                $devis->setIsCloturer(true);
                $em->persist($bon_commande);
                $em->flush();
                $response = new Response(json_encode(array('success' => true)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        $lignes = array();
        foreach ($devis->getLignesDevis() as $k => $ligne) {
            $lignes[$k] = $ligne;
        }
        return $this->render('GdsVenteBundle:Devis:devis_to_bon_commande.html.twig', array('form' => $form->createView(), 'lignes' => $lignes, 'id' => $id, 'user' => $user));
    }

    public function livrerAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $request = $this->getRequest();
        $id = $request->get('id');
        $devis = $em->getRepository('GdsVenteBundle:Devis')->find($id);
        $client = $devis->getClient();
        $bon_livraison = new BonLivraisonClient();
        $societe = $em->getRepository('GdsArticleBundle:Societe')->findAll()[0];
        $pref = $societe->getPrefixeBonLivraison();
        $num = $societe->getNumeroBonLivraison();
        $bon_livraison->setReference($pref . ' ' . $num);
        $form = $this->createForm(new BonLivraisonClientType, $bon_livraison);
        $user = $this->getUser();
        if ($request->isMethod('POST')) {
            try {
                $articles = json_decode($request->get('articles'));
                if (count($articles->articles) == 0) {
                    $response = new Response(json_encode(array('success' => false)));
                    $response->headers->set('Content-Type', 'application/json');
                    return $response;
                }
                $history_bon_livraison = new HistoryBonLivraisonClient();
                $heure = $request->get('heure');
                $form->bind($request);
                $bon_livraison = $form->getData();
                $client = $bon_livraison->getClient();
                $passager = false;
                if ($client->getRaisonSocial() == 'PASSAGER')
                    $passager = true;
                $is_facturable = $request->get('facturable');
                $nom_dep = $request->get('departement');
                $departement = $em->getRepository('GdsArticleBundle:Departement')->findOneByNom($nom_dep);
                $bon_livraison->setHeure($heure);
                $montant_bl_ttc = 0;
                $montant_noir_ttc = 0;
                foreach ($articles->articles as $json_article) {
                    $article = $em->getRepository('GdsArticleBundle:Article')->find($json_article->id);
                    $stock = $em->getRepository('GdsArticleBundle:Stock')->findOneBy(array('article' => $article, 'departement' => $departement));
                    if ($is_facturable == 'true')
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock, 'is_noir' => 0), array('prix_achat_ttc' => 'ASC'));
                    else
                        $stock_achat = $em->getRepository('GdsAchatBundle:StockAchat')->findBy(array('stock' => $stock), array('is_noir' => 'DESC', 'prix_achat_ttc' => 'ASC'));
                    $quantite = $json_article->quantite;
                    $quantite_blanc = 0;
                    $quantite_noir = 0;
                    $prix_achat_ttc = 0;
                    $i = 0;
                    $count_stock_achat = count($stock_achat);
                    while ($quantite > 0 && $i < $count_stock_achat) {
                        if ($quantite <= $stock_achat[$i]->getQuantite()) {
                            $stock_achat[$i]->setQuantite($stock_achat[$i]->getQuantite() - $quantite);
                            $prix_achat_ttc += $stock_achat[$i]->getPrixAchatTtc() * $quantite;
                            if ($stock_achat[$i]->getIsNoir())
                                $quantite_noir += $quantite;
                            else
                                $quantite_blanc += $quantite;
                            $quantite = 0;
                        } else {
                            $prix_achat_ttc += $stock_achat[$i]->getPrixAchatTtc() * $stock_achat[$i]->getQuantite();
                            if ($stock_achat[$i]->getIsNoir())
                                $quantite_noir += $stock_achat[$i]->getQuantite();
                            else
                                $quantite_blanc += $stock_achat[$i]->getQuantite();
                            $quantite -= $stock_achat[$i]->getQuantite();
                            $stock_achat[$i]->setQuantite(0);
                            $em->remove($stock_achat[$i]);
                        }
                        $i++;
                    }
                    if ($quantite > 0) {
                        $prix_achat_ttc += $article->getPrixAchatHt() * (1 + $article->getTauxTva() / 100) * $quantite;
                        if ($is_facturable == 'true')
                            $quantite_blanc += $quantite;
                        else {
                            $q_n = $stock->getQuantiteNoir() - $quantite_noir;
                            $q_b = $stock->getQuantiteBlanc() - $quantite_blanc;
                            if ($quantite <= $q_n || $q_b <= 0) {
                                $quantite_noir += $quantite;
                            } else {
                                if ($q_n > 0) {
                                    $quantite_noir += $q_n;
                                    $quantite -=$q_n;
                                }
                                if ($q_b >= $quantite) {
                                    $quantite_blanc +=$quantite;
                                } else {
                                    $quantite_blanc +=$q_b;
                                    $quantite_noir = $quantite_noir + $quantite - $q_b;
                                }
                            }
                        }
                    }
                    $stock->setQuantiteBlanc($stock->getQuantiteBlanc() - $quantite_blanc);
                    $stock->setQuantiteNoir($stock->getQuantiteNoir() - $quantite_noir);
                    $prix_achat_ttc /= $json_article->quantite;
                    $prix_vente = $json_article->prix_vente;
                    $taux_tva = $json_article->taux_tva;
                    $remise = $json_article->remise;
                    $prix_vente_ttc = $prix_vente * (1 + $taux_tva / 100) * (1 - $remise / 100);
                    $prix_vente_ttc = round($prix_vente_ttc, 3);
                    $montant_bl_ttc += $prix_vente_ttc * $quantite_blanc;
                    $montant_noir_ttc += $prix_vente_ttc * $quantite_noir;
                    $ligne = new LigneBonLivraisonClient();
                    $ligne->setArticle($article);
                    $ligne->setQuantiteBlanc($quantite_blanc);
                    $ligne->setQuantiteNoir($quantite_noir);
                    $ligne->setPrixUnitaireHt($prix_vente);
                    $ligne->setPrixAchatTtc($prix_achat_ttc);
                    $ligne->setTauxRemise($remise);
                    $ligne->setTauxTva($taux_tva);
                    $bon_livraison->addLignesBonLivraison($ligne);

                    $history_ligne = new HistoryLigneBonLivraisonClient();
                    $history_ligne->setArticle($article);
                    $history_ligne->setQuantiteBlanc($quantite_blanc);
                    $history_ligne->setQuantiteNoir($quantite_noir);
                    $history_ligne->setPrixUnitaireHt($prix_vente);
                    $history_ligne->setPrixAchatTtc($prix_achat_ttc);
                    $history_ligne->setTauxRemise($remise);
                    $history_ligne->setTauxTva($taux_tva);
                    $history_bon_livraison->addHistoryLignesBonLivraison($history_ligne);
                    if (!$passager) {
                        $categorie_remise = $em->getRepository('GdsVenteBundle:CategorieRemise')->findOneBy(array('client' => $client, 'article' => $article));
                        if ($categorie_remise != null)
                            $categorie_remise->setRemise($remise);
                        else {
                            $categorie_remise = new CategorieRemise();
                            $categorie_remise->setArticle($article);
                            $categorie_remise->setClient($client);
                            $categorie_remise->setRemise($remise);
                            $em->persist($categorie_remise);
                        }
                    }
                }
                $ref_num = $societe->getNumeroBonLivraison();
                $societe->setNumeroBonLivraison($ref_num + 1);
                $bon_livraison->setReference($pref . ' ' . $ref_num);
                $bon_livraison->setReste($montant_bl_ttc + $montant_noir_ttc);
                $bon_livraison->setMontantBlancTtc($montant_bl_ttc);
                $bon_livraison->setMontantNoirTtc($montant_noir_ttc);
                $bon_livraison->setUser($user);
                $bon_livraison->setDevis($devis);
                $bon_livraison->setDepartement($departement);
                $solde_client = $client->getSolde();
                $limite_credit = $client->getLimiteCredit();
                if ($solde_client + $montant_bl_ttc + $montant_noir_ttc > $limite_credit) {
                    $mdp = $request->get('mdp');
                    $code_secret = $societe->getCodeSecret();
                    if ($mdp != $code_secret) {
                        $response = new Response(json_encode(array('limit_depass' => true)));
                        $response->headers->set('Content-Type', 'application/json');
                        return $response;
                    }
                }
                $client->setSolde($solde_client + $montant_bl_ttc + $montant_noir_ttc);
                $history_bon_livraison->setReference($pref . ' ' . $ref_num);
                $history_bon_livraison->setDepartement($departement);
                $history_bon_livraison->setReste($montant_bl_ttc + $montant_noir_ttc);
                $history_bon_livraison->setMontantBlancTtc($montant_bl_ttc);
                $history_bon_livraison->setMontantNoirTtc($montant_noir_ttc);
                $history_bon_livraison->setUser($user);
                $history_bon_livraison->setDate($bon_livraison->getDate());
                $history_bon_livraison->setHeure($bon_livraison->getHeure());
                $history_bon_livraison->setClient($bon_livraison->getClient());
                $em->persist($bon_livraison);
                $em->persist($history_bon_livraison);
                $em->flush();
                $response = new Response(json_encode(array('success' => true, 'numero' => $ref_num)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            } catch (Exception $e) {
                $response = new Response(json_encode(array('success' => false)));
                $response->headers->set('Content-Type', 'application/json');
                return $response;
            }
        }
        $lignes = array();
        foreach ($devis->getLignesDevis() as $k => $ligne) {
            $lignes[$k] = $ligne;
        }
        return $this->render('GdsVenteBundle:Devis:devis_to_bon_livraison.html.twig', array('form' => $form->createView(), 'lignes' => $lignes, 'id' => $id, 'user' => $user, 'client' => $client));
    }

    function int2str($a) {
        if ($a < 0)
            return 'moins ' . $this->int2str(-$a);
        if ($a < 17) {
            switch ($a) {
                case 0: return 'zero';
                case 1: return 'un';
                case 2: return 'deux';
                case 3: return 'trois';
                case 4: return 'quatre';
                case 5: return 'cinq';
                case 6: return 'six';
                case 7: return 'sept';
                case 8: return 'huit';
                case 9: return 'neuf';
                case 10: return 'dix';
                case 11: return 'onze';
                case 12: return 'douze';
                case 13: return 'treize';
                case 14: return 'quatorze';
                case 15: return 'quinze';
                case 16: return 'seize';
            }
        } else if ($a < 20) {
            return 'dix-' . $this->int2str($a - 10);
        } else if ($a < 100) {
            if ($a % 10 == 0) {
                switch ($a) {
                    case 20: return 'vingt';
                    case 30: return 'trente';
                    case 40: return 'quarante';
                    case 50: return 'cinquante';
                    case 60: return 'soixante';
                    case 70: return 'soixante-dix';
                    case 80: return 'quatre-vingt';
                    case 90: return 'quatre-vingt-dix';
                }
            } else if ($a < 70) {
                return $this->int2str($a - $a % 10) . ' ' . $this->int2str($a % 10);
            } else if ($a < 80) {
                return $this->int2str(60) . ' ' . $this->int2str($a % 20);
            } else {
                return $this->int2str(80) . ' ' . $this->int2str($a % 20);
            }
        } else if ($a == 100) {
            return 'cent';
        } else if ($a < 200) {
            return $this->int2str(100) . ' ' . $this->int2str($a % 100);
        } else if ($a < 1000) {
            if (($a % 100) > 0)
                return $this->int2str((int) ($a / 100)) . ' ' . $this->int2str(100) . ' ' . $this->int2str($a % 100);
            else
                return $this->int2str((int) ($a / 100)) . ' ' . $this->int2str(100);
        } else if ($a == 1000) {
            return 'mille';
        } else if ($a < 2000) {
            return $this->int2str(1000) . ' ' . $this->int2str($a % 1000) . ' ';
        } else if ($a < 1000000) {
            return $this->int2str((int) ($a / 1000)) . ' ' . $this->int2str(1000) . ' ' . $this->int2str($a % 1000);
        }
    }

    function chiffre_to_lettre($a) {
        $total = explode(".", $a);
        $dinars = $total[0];
        $millimes = 0;
        if (count($total) == 2) {
            $millimes = $total[1];
            $a = number_format($a, 3);
            $index_point = strpos($a, '.');
            $i = $index_point + 1;
            if ($a[$i] != 0) {
                if ($a[$i + 1] != 0) {
                    if ($a[$i + 2] != 0) {
                        //rien
                    } else {
                        $millimes*=10;
                    }
                } else {
                    if ($a[$i + 2] != 0) {
                        //rien
                    } else {
                        $millimes*=100;
                    }
                }
            } else {
                if ($a[$i + 1] != 0) {
                    if ($a[$i + 2] != 0) {
                        //rien
                    } else {
                        $millimes*=10;
                    }
                } else {
                    if ($a[$i + 2] != 0) {
                        //rien
                    } else {
                        //rien
                    }
                }
            }
        }
        $lettre = $this->int2str($dinars) . " dinars et " . $this->int2str($millimes) . " millimes";
        return $lettre;
    }

}
